package com.example.geoaimavlink_android.activity.view;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.geoaimavlink_android.R;
import com.example.geoaimavlink_android.activity.data.ChannelType;
import com.example.geoaimavlink_android.activity.data.KeyItemActionListener;
import com.example.geoaimavlink_android.activity.data.KeyItemSetParamListener;
import com.example.geoaimavlink_android.utils.ApiSelectUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class KeyValueDialogUtil {

    public static void showApiSetParamAndInvokeWindow(View anchor, Method method, KeyItemSetParamListener listener) {
        Context context = anchor.getContext();
        View rootView = View.inflate(context, R.layout.window_set_api_param, null);
        LinearLayout llItemBase = rootView.findViewById(R.id.ll_frame);

        //如果最后是监听类型，可以跳过
        int paramLen = method.getParameterTypes().length;
        if (method.getParameterTypes()[paramLen - 1].getName().endsWith("ICompletionCallback")) {
            paramLen = paramLen - 1;
        }
        for (int i = 0; i < paramLen; i++) {
            if (isParamEnum(method.getParameterTypes()[i])) {
                Spinner spinner = new Spinner(anchor.getContext());
                Field[] fields = method.getParameterTypes()[i].getFields();
                String[] items = new String[fields.length];
                for (int j = 0; j < fields.length; j++) {
                    items[j] = fields[j].getName();
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(anchor.getContext(), android.R.layout.simple_spinner_item, items);
                spinner.setAdapter(adapter);
                llItemBase.addView(spinner);
            } else {
                String name = method.getParameterTypes()[i].getName();
                EditText editText = new EditText(anchor.getContext());
                editText.setHint(name);
                llItemBase.addView(editText);
            }
        }

        final PopupWindow window = new PopupWindow(context);
        window.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setOutsideTouchable(true);
        window.setTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new ColorDrawable(0xffffff));
        window.setContentView(rootView);
        window.showAsDropDown(anchor, anchor.getWidth(), -anchor.getHeight());

        rootView.findViewById(R.id.btn_cancel).setOnClickListener(v -> {
            window.dismiss();
        });


        rootView.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            ArrayList<Object> objResult = new ArrayList<>();
            //遍历集合体的view，确认参数类型
            for (int i = 0; i < llItemBase.getChildCount(); i++) {
                View view = llItemBase.getChildAt(i);
                Object paramInvoke = null;
                if (view instanceof Spinner) {
                    String enumName = ((String)((Spinner) view).getSelectedItem());
                    try {
                        paramInvoke = method.getParameterTypes()[i].getField(enumName).get(null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (view instanceof EditText) {
                    String paramType = method.getParameterTypes()[i].getName();
                    paramInvoke = ApiSelectUtils.getInstance().getParamInvoke(paramType, ((EditText) view).getText().toString());
                }
                if (paramInvoke != null) objResult.add(paramInvoke);
            }

            listener.onResult(objResult.toArray(new Object[0]));

            window.dismiss();
        });
    }

    public static  void showChannelFilterListWindow(View anchor, final List<ChannelType> sourceData , final KeyItemActionListener<ChannelType> callback) {
        if (anchor == null || anchor.getContext() == null) {
            return;
        }
        Context context = anchor.getContext();
        View rootView = View.inflate(context, R.layout.window_simple_listview, null);
        final PopupWindow window = new PopupWindow(context);
        window.setWidth(getHeight(context) / 2);
        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setOutsideTouchable(true);
        window.setTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new ColorDrawable(0xffffff));

        window.setContentView(rootView);
        window.showAsDropDown(anchor, (int) (anchor.getWidth() * 1.5), - dip2px(anchor.getContext(), 37), Gravity.LEFT | Gravity.BOTTOM);
        ListView listView = rootView.findViewById(R.id.list_view);

        ArrayList<String> dataAdapter = new ArrayList<>();
        for (ChannelType datum : sourceData) {
            dataAdapter.add(datum.getKey());
        }

        ArrayAdapter<String> sourceAdapter = new ArrayAdapter<>(context, R.layout.item_textview, dataAdapter);

        listView.setAdapter(sourceAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (callback != null ) {
                TextView tv = view.findViewById(R.id.tv_item);
                String s = tv.getText().toString();

                for (int i = 0; i < sourceData.size(); i++) {
                    if (sourceData.get(i).getKey().equals(s)) {
                        callback.actionChange(sourceData.get(i));
                        window.dismiss();
                        return;
                    }
                }
            }
        });

        EditText filter = rootView.findViewById(R.id.et_filter);
        filter.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // dosomething
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // dosomething
            }

            @Override
            public void afterTextChanged(Editable s) {
                sourceAdapter.getFilter().filter(s.toString());
            }
        });
    }

    public static boolean isParamEnum(Class<?> parameterType) {
        return parameterType.isEnum();
    }

    public static int getHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        Display display = getResolution(context);
        display.getMetrics(dm);
        return dm.heightPixels;
    }

    public static Display getResolution(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
